<template>
  <div class="user-management">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2 class="page-title">用户管理</h2>
      <el-button type="primary" @click="openAddDialog" class="add-btn">
        <el-icon><Plus /></el-icon>新增用户
      </el-button>
    </div>

    <!-- 搜索和筛选区域 -->
    <div class="filter-container">
      <el-input
        v-model="searchQuery"
        placeholder="搜索用户名/真实姓名/电话"
        class="search-input"
        clearable
        @keyup.enter="fetchUsers"
        @clear="fetchUsers"
      >
        <template #append>
          <el-button @click="fetchUsers" class="search-btn">
            <el-icon><Search /></el-icon>
          </el-button>
        </template>
      </el-input>

      <el-select
        v-model="roleFilter"
        placeholder="按角色筛选"
        clearable
        @change="fetchUsers"
        class="role-select"
      >
        <el-option
          v-for="role in roleOptions"
          :key="role.value"
          :label="role.label"
          :value="role.value"
        />
      </el-select>

      <el-select
        v-model="statusFilter"
        placeholder="按状态筛选"
        clearable
        @change="fetchUsers"
        class="status-select"
      >
        <el-option
          v-for="status in statusOptions"
          :key="status.value"
          :label="status.label"
          :value="status.value"
        />
      </el-select>
    </div>

    <!-- 用户列表 -->
    <el-table
      :data="pagedData"
      border
      stripe
      v-loading="loading"
      style="width: 100%; margin-top: 20px;"
      class="user-table"
      :row-class-name="tableRowClassName"
    >
      <el-table-column prop="userId" label="用户ID" width="100" align="center" />
      <el-table-column prop="userName" label="用户名" width="150" />
      <el-table-column prop="realName" label="真实姓名" width="120" />
      <el-table-column prop="telephone" label="电话" width="150" />
      <el-table-column label="角色" width="120" align="center">
    <template #default="{row}">
      <el-tag :type="getRoleTagType(row.userRole)" class="role-tag">
        {{ formatRole(row.userRole) }}
      </el-tag>
    </template>
  </el-table-column>
  
  <el-table-column label="状态" width="100" align="center">
    <template #default="{row}">
      <el-tag :type="row.status === 'blacklisted' ? 'danger' : 'success'" class="status-tag">
        {{ formatStatus(row.status) }}
      </el-tag>
    </template>
  </el-table-column>
      <el-table-column label="最后登录" width="180" align="center">
        <template #default="{row}">
          <span class="date-text">{{ formatDate(row.lastLogin) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="loginCount" label="登录次数" width="100" align="center" />
      <el-table-column label="创建时间" width="180" align="center">
        <template #default="{row}">
          <span class="date-text">{{ formatDate(row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="220" fixed="right" align="center">
        <template #default="{row}">
          <div class="action-buttons">
            <el-button 
              size="small" 
              type="warning" 
              @click="openResetPasswordDialog(row)"
              v-if="hasPermission('resetPassword')"
              class="action-btn"
            >
              重置密码
            </el-button>
            <el-button 
              size="small" 
              :type="row.status === 'blacklisted' ? 'success' : 'danger'" 
              @click="handleToggleBlacklist(row)"
              v-if="hasPermission('manageBlacklist')"
              class="action-btn"
            >
              {{ row.status === 'blacklisted' ? '恢复' : '拉黑' }}
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="filteredUsers.length"
        :page-sizes="[10, 20, 30, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        class="custom-pagination"
      />
    </div>

    <!-- 新增用户对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="新增用户"
      width="50%"
      class="user-dialog"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        label-position="right"
      >
        <el-form-item label="用户名" prop="userName">
          <el-input 
            v-model="form.userName" 
            placeholder="请输入用户名"
            class="form-input"
          />
        </el-form-item>
        
        <el-form-item label="真实姓名" prop="realName">
          <el-input v-model="form.realName" placeholder="请输入真实姓名" class="form-input" />
        </el-form-item>
        
        <el-form-item label="电话" prop="telephone">
          <el-input v-model="form.telephone" placeholder="请输入电话号码" class="form-input" />
        </el-form-item>
        
        <el-form-item label="用户角色" prop="userRole">
          <el-select 
            v-model="form.userRole" 
            placeholder="请选择用户角色"
            class="role-select"
          >
            <el-option
              v-for="role in roleOptions"
              :key="role.value"
              :label="role.label"
              :value="role.value"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="密码" prop="password">
          <el-input 
            v-model="form.password" 
            placeholder="请输入密码" 
            type="password"
            show-password
            class="form-input"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false" class="cancel-btn">取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="submitting" class="confirm-btn">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 重置密码对话框 -->
    <el-dialog
      v-model="resetPasswordDialogVisible"
      title="重置密码"
      width="30%"
      class="reset-dialog"
    >
      <div class="reset-content">
        确定要将用户 <strong>{{ currentUser.realName || currentUser.userName }}</strong> 的密码重置为 <strong>123456</strong> 吗？
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="resetPasswordDialogVisible = false" class="cancel-btn">取消</el-button>
          <el-button type="primary" @click="resetPassword" :loading="resetting" class="confirm-btn">
            确认重置
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { Plus, Search } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'

// 数据状态
const loading = ref(false)
const userList = ref([])
const searchQuery = ref('')
const roleFilter = ref('')
const statusFilter = ref('')

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)

// 表单相关
const dialogVisible = ref(false)
const submitting = ref(false)
const formRef = ref(null)
const form = ref({
  userId: null,
  userName: '',
  telephone: '',
  password: '123456', // 默认密码
  realName: '',
  userRole: 'user',
  status: 'active'
})

// 重置密码相关
const resetPasswordDialogVisible = ref(false)
const resetting = ref(false)
const currentUser = ref({})

// 角色选项
const roleOptions = [
  { value: 'admin', label: '管理员' },
  { value: 'doctor', label: '医生' },
  { value: 'user', label: '普通用户' }
]

// 状态选项
const statusOptions = [
  { value: 'active', label: '正常' },
  { value: 'blacklisted', label: '已拉黑' }
]

// 表单验证规则
const rules = {
  userName: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在3到20个字符', trigger: 'blur' }
  ],
  realName: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在2到20个字符', trigger: 'blur' }
  ],
  telephone: [
    { required: true, message: '请输入电话号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  userRole: [
    { required: true, message: '请选择用户角色', trigger: 'change' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在6到20个字符', trigger: 'blur' }
  ]
}

// 计算属性
const filteredUsers = computed(() => {
  let result = userList.value
  
  // 按搜索词过滤
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    result = result.filter(user => {
      return (
        (user.userName && user.userName.toLowerCase().includes(query)) ||
        (user.realName && user.realName.toLowerCase().includes(query)) ||
        (user.telephone && user.telephone.includes(query))
      )
    })
  }
  
  // 按角色过滤
  if (roleFilter.value) {
    result = result.filter(user => user.userRole === roleFilter.value)
  }
  
  // 按状态过滤
  if (statusFilter.value) {
    result = result.filter(user => user.status === statusFilter.value)
  }
  
  return result
})

const pagedData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredUsers.value.slice(start, end)
})

// 获取用户列表
const fetchUsers = async () => {
  try {
    loading.value = true
    const response = await axios.get('http://localhost:8080/hospital5_war/user/findAll')
    // 确保每个用户都有status属性，默认为active
    userList.value = (response.data || []).map(user => ({
      ...user,
      status: user.status || 'active'
    }))
  } catch (error) {
    console.error('获取用户列表失败:', error)
    ElMessage.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

// 格式化日期
const formatDate = (timestamp) => {
  if (!timestamp) return ''
  return new Date(timestamp).toLocaleString()
}

// 格式化角色显示
const formatRole = (role) => {
  const roleMap = {
    admin: '管理员',
    doctor: '医生',
    user: '普通用户'
  }
  return roleMap[role] || role
}

// 格式化状态显示
const formatStatus = (status) => {
  const statusMap = {
    active: '正常',
    blacklisted: '已拉黑'
  }
  return statusMap[status] || status
}

// 获取角色标签类型
const getRoleTagType = (role) => {
  const typeMap = {
    admin: 'danger',    // 管理员用红色
    doctor: 'warning',  // 医生用黄色
    user: 'success'     // 普通用户用绿色
  }
  return typeMap[role] || ''  // 默认返回空字符串
}

// 表格行样式
const tableRowClassName = ({ row }) => {
  if (row.status === 'blacklisted') {
    return 'blacklisted-row'
  }
  return ''
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
}

const handleCurrentChange = (val) => {
  currentPage.value = val
}

// 打开新增对话框
const openAddDialog = () => {
  form.value = {
    userId: null,
    userName: '',
    telephone: '',
    password: '123456',
    realName: '',
    userRole: 'user',
    status: 'active'
  }
  dialogVisible.value = true
}

// 打开重置密码对话框
const openResetPasswordDialog = (user) => {
  currentUser.value = { ...user }
  resetPasswordDialogVisible.value = true
}

// 提交表单
const submitForm = async () => {
  try {
    await formRef.value.validate()
    submitting.value = true
    
    const config = {
      headers: {
        'Content-Type': 'application/json'
      }
    }
    
    // 新增用户
    await axios.post('http://localhost:8080/hospital5_war/user/addUser', form.value, config)
    ElMessage.success('用户添加成功')
    
    dialogVisible.value = false
    fetchUsers()
  } catch (error) {
    console.error('操作失败:', error)
    if (error.response?.status === 409) {
      ElMessage.error('用户名已存在')
    } else {
      ElMessage.error(error.response?.data?.message || '操作失败，请稍后重试')
    }
  } finally {
    submitting.value = false
  }
}

// 重置密码
const resetPassword = async () => {
  try {
    resetting.value = true
    const response = await axios.post('http://localhost:8080/hospital5_war/user/resetPassword', {
      userId: currentUser.value.userId
    })
    
    if (response.data.success) {
      ElMessage.success(response.data.message)
      resetPasswordDialogVisible.value = false
      fetchUsers()
    } else {
      ElMessage.error(response.data.message || '密码重置失败')
    }
  } catch (error) {
    console.error('重置密码失败:', error)
    ElMessage.error(error.response?.data?.message || '重置密码失败')
  } finally {
    resetting.value = false
  }
}

// 切换用户拉黑状态
const handleToggleBlacklist = async (user) => {
  try {
    const action = user.status === 'blacklisted' ? '恢复' : '拉黑'
    await ElMessageBox.confirm(`确定要${action}用户 ${user.realName || user.userName} 吗?`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const newStatus = user.status === 'blacklisted' ? 'active' : 'blacklisted'
    // 使用updateUserInfo接口来更新状态
    const response = await axios.post('http://localhost:8080/hospital5_war/user/updateUserInfo', {
      userId: user.userId,
      status: newStatus
    }, {
      headers: {
        'Content-Type': 'application/json'
      }
    })
    
    if (response.data) {
      ElMessage.success(`${action}用户成功`)
      fetchUsers()
    } else {
      ElMessage.error(`${action}用户失败`)
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('操作失败:', error)
      ElMessage.error(error.response?.data?.message || '操作失败')
    }
  }
}

// 权限检查
const hasPermission = (permission) => {
  // 这里可以根据当前登录用户的角色来判断权限
  // 示例中简单返回true，实际项目中应根据用户角色判断
  return true
}

// 初始化加载数据
onMounted(() => {
  fetchUsers()
})
</script>

<style scoped>
.user-management {
  padding: 24px;
  background-color: #fff;
  font-family: 'Helvetica Neue', Helvetica, 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', Arial, sans-serif;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.page-title {
  font-size: 20px;
  font-weight: 600;
  color: #303133;
  margin: 0;
}

.add-btn {
  font-size: 14px;
  height: 36px;
}

.filter-container {
  display: flex;
  gap: 16px;
  margin-bottom: 20px;
  align-items: center;
}

.search-input {
  width: 320px;
}

.search-input :deep(.el-input-group__append) {
  background-color: #409EFF;
  color: white;
}

.search-input :deep(.el-input-group__append:hover) {
  background-color: #66b1ff;
}

.search-btn {
  color: white;
}

.role-select, .status-select {
  width: 180px;
}

.user-table {
  font-size: 14px;
}

.user-table :deep(th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 600;
}

.user-table :deep(td) {
  padding: 12px 0;
}

.user-table :deep(.blacklisted-row) {
  color: #999;
  background-color: #f9f9f9;
}

.user-table :deep(.blacklisted-row:hover > td) {
  background-color: #f0f0f0 !important;
}

.role-tag, .status-tag {
  font-size: 13px;
  padding: 0 8px;
  height: 24px;
  line-height: 24px;
}

.date-text {
  font-size: 13px;
  color: #606266;
}

.action-buttons {
  display: flex;
  gap: 8px;
}

.action-btn {
  font-size: 12px;
  padding: 7px 12px;
}

.pagination-container {
  margin-top: 24px;
  display: flex;
  justify-content: flex-end;
}

.custom-pagination {
  padding: 12px 0;
}

.user-dialog :deep(.el-dialog__header) {
  border-bottom: 1px solid #e8e8e8;
  margin-right: 0;
  padding: 16px 24px;
}

.user-dialog :deep(.el-dialog__title) {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.form-input {
  width: 100%;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding-top: 16px;
  border-top: 1px solid #e8e8e8;
}

.cancel-btn {
  width: 80px;
}

.confirm-btn {
  width: 80px;
}

.reset-dialog :deep(.el-dialog__header) {
  border-bottom: 1px solid #e8e8e8;
  margin-right: 0;
  padding: 16px 24px;
}

.reset-dialog :deep(.el-dialog__title) {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.reset-content {
  font-size: 14px;
  line-height: 1.6;
  color: #606266;
  padding: 0 8px;
}

.reset-content strong {
  color: #303133;
  font-weight: 600;
}
</style>